from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required

from .. import db
from app.models.Shop import Shop
from app.utils.response import success_api, fail_api
from app.utils.validator import validate_params
import uuid
from datetime import datetime
from ..base import base



# 获取店铺列表
@base.route('/shop/list', methods=['GET'])
@jwt_required()
def get_shop_list():
    try:
        # 获取查询参数
        shop_name = request.args.get('shopName')
        shop_status = request.args.get('shopStatus')
        page_num = int(request.args.get('pageNum', 1))
        page_size = int(request.args.get('pageSize', 10))


        # 构建查询条件
        query = Shop.query
        if shop_name:
            query = query.filter(Shop.shop_name.like(f'%{shop_name}%'))
        if shop_status:
            query = query.filter(Shop.shop_status == shop_status)

        # 分页查询
        total = query.count()
        shops = query.offset((page_num - 1) * page_size).limit(page_size).all()
        
        # 返回结果
        return success_api({
            'total': total,
            'rows': [shop.to_dict() for shop in shops]
        })
    except Exception as e:
        return fail_api(msg=str(e))

# 获取店铺详情
@base.route('/shop/<shop_id>', methods=['GET'])
@jwt_required()
def get_shop(shop_id):
    try:
        shop = Shop.query.get(shop_id)
        if not shop:
            return fail_api(msg='店铺不存在')
        return success_api(data=shop.to_dict())
    except Exception as e:
        return fail_api(msg=str(e))

# 新增店铺
@base.route('/shop', methods=['POST'])
@jwt_required()
def add_shop():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['shopName', 'shopStatus', 'ownerId']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 创建店铺对象
        shop = Shop(
            shop_id=str(uuid.uuid4()),
            shop_name=data.get('shopName'),
            shop_desc=data.get('shopDesc'),
            shop_logo=data.get('shopLogo'),
            shop_status=data.get('shopStatus'),
            owner_id=data.get('ownerId'),
            remark=data.get('remark')
        )

        # 保存到数据库
        db.session.add(shop)
        db.session.commit()

        return success_api(msg='添加成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 修改店铺
@base.route('/shop', methods=['PUT'])
@jwt_required()
def update_shop():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['shopId', 'shopName', 'shopStatus']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 查询店铺
        shop = Shop.query.get(data.get('shopId'))
        if not shop:
            return fail_api(msg='店铺不存在')

        # 更新店铺信息
        shop.shop_name = data.get('shopName')
        shop.shop_desc = data.get('shopDesc')
        shop.shop_logo = data.get('shopLogo')
        shop.shop_status = data.get('shopStatus')
        shop.remark = data.get('remark')
        shop.update_time = datetime.now()

        # 保存到数据库
        db.session.commit()

        return success_api(msg='修改成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 删除店铺
@base.route('/shop/<shop_id>', methods=['DELETE'])
@jwt_required()
def delete_shop(shop_id):
    try:
        shop = Shop.query.get(shop_id)
        if not shop:
            return fail_api(msg='店铺不存在')

        # 从数据库中删除
        db.session.delete(shop)
        db.session.commit()

        return success_api(msg='删除成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))